package com.cbtx.module_sp.ui.fragment

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.cbtx.module.base.ui.BaseVMFragment
import com.cbtx.module.common.ui.GoodsAdapter
import com.cbtx.module_sp.ui.vm.GoodsTreasureFragmentVM
import com.cbtx.module_sp.MyApplication
import com.cbtx.module_sp.R
import com.cbtx.module_sp.ui.activity.GoodsDetailActivity
import com.txcb.lib.base.view.SpaceItemDecoration
import kotlinx.android.synthetic.main.sp_fragment_goods.*
import kotlinx.android.synthetic.main.sp_fragment_renzheng.mTvCode

/**
 * 收藏宝
 */
class GoodsTreasureFragment: BaseVMFragment<GoodsTreasureFragmentVM>() {

    var mAdapter: GoodsAdapter? = null

    override fun getPresenterClazz(): Class<GoodsTreasureFragmentVM> {
         return GoodsTreasureFragmentVM::class.java
    }


    override fun setLayout(): Any {
        return R.layout.sp_fragment_goods
    }

    override fun initView(view: View?, savedInstanceState: Bundle?) {


        mTvCode.text = "云屏编码:${MyApplication.mAndroidId}"

        mVM.init()

        mAdapter = GoodsAdapter(mVM.mDatas,283)
        mRvGoods.layoutManager = GridLayoutManager(activity,4)
        mRvGoods.addItemDecoration(SpaceItemDecoration(30))
        mRvGoods.adapter = mAdapter


        mVM.mDataLoadStatus.observe(this, Observer {

            if (it == mVM.loadFirst){
                //从缓存读取到的数据
                mAdapter?.notifyDataSetChanged()
            }else{
                mAdapter?.setEnableLoadMore(true)
                mRefreshView.isRefreshing = false

                mAdapter?.notifyDataSetChanged()
                if (mVM.mCanLoadMore){
                    mAdapter?.loadMoreComplete()
                }else{
                    mAdapter?.loadMoreEnd()
                }
            }
        })


        mAdapter?.setOnItemClickListener { adapter, view, position ->
            val renZhengItem = mVM.mDatas?.get(position)
            GoodsDetailActivity.start(activity!!,renZhengItem)
        }

        //刷新
        mRefreshView.setOnRefreshListener {
            mVM.requestData(true)
        }
        //加载更多
        mAdapter?.setOnLoadMoreListener({
            if (mVM.mCanLoadMore){
                mVM.requestData(false)
            }else{
                mAdapter?.loadMoreEnd()
            }
        },mRvGoods)
    }

    override fun lazyData() {
        super.lazyData()

        mAdapter?.setEnableLoadMore(false)
        mVM.requestData(true)
    }
}